package com.webdev.dao.imp;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.PreparedStatement;
import com.webdev.dao.PersonnelDao;
import com.webdev.domain.Personnel;

public class PersonnelDaoImp implements PersonnelDao {
    static MySql mysql = new MySql();
	private static Personnel getPersonnel(String sql) {
		Personnel personnel = new Personnel();
		Connection con=mysql.getConn();
		PreparedStatement pstmt;
		try {
	    	
	        pstmt = (PreparedStatement)con.prepareStatement(sql);
	        ResultSet rs = pstmt.executeQuery();
	        while(rs.next()){ 	    		
	            personnel.setPid(rs.getInt("pid"));
	            personnel.setPname(rs.getString("pname"));
	            personnel.setUsername(rs.getString("username"));
	            personnel.setPassword(rs.getString("password"));
	            personnel.setPidentity(rs.getString("pidentity"));
	        } 
	        pstmt.close();
	        con.close();
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
		return personnel;
	}
	@Override
	public boolean logIn(String username, String password){
		boolean state = false;
		String sql = "select * from personnel where username='" + username + "';";
		Connection con=mysql.getConn();
		PreparedStatement pstmt;
		try {	    	
	        pstmt = (PreparedStatement)con.prepareStatement(sql);
	        ResultSet rs = pstmt.executeQuery();
	        while(rs.next()){ 	    		
	            if (password.equals(rs.getString("password"))) {
	            	state=true;
	            }
	        } 
	        pstmt.close();
	        con.close();
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
		return state;
	}
	@Override
	public Personnel getPersonnelByUsername(String username) {
		String sql = "select * from personnel where username='" + username + "';";
        return getPersonnel(sql);
	}
	@Override
	public Personnel getPersonnelById(int pid) {
		String sql = "select * from personnel where pid=" + pid + ";";
		return getPersonnel(sql);
	}

}
